package org.ccay.validator.validators;

import org.ccay.core.util.StringUtil;
import org.ccay.validator.ValidatorSystemException;
import com.opensymphony.xwork2.validator.ValidationException;

/**
 * 使用示例
 *  <field name="sqlTraceLevel">
 *  <field-validator type="numericLimit">
 *     <param name="inLength">1,4,8,12</param> //注意：只能是“,”分隔的数字字符串
 *     <message key="ccay.logs.validate.sqlTraceLevel">SqlTraceLevel length can be 1,4,8,or 12.</message>
 *  </field-validator>
 *  </field>
 */

/**
 * 字符串长度验证
 * 
 * 
 * @since 2013-04-09
 */
public class NumericLimitValidator extends AbstractFieldValidator {

	private String inLength; // "," 分割的字符串， 如 1,4,8,12

	public String getInLength() {
		return inLength;
	}

	public void setInLength(String inLength) {
		this.inLength = inLength;
	}

	public void validate(Object object) throws ValidationException,
			ValidatorSystemException {
		// 获取验证属性名称
		String fieldName = getFieldName();
		// 获取当前属性的value
		String fieldValue = getFieldValue(fieldName, object).toString();
		// 如果为空 就不校验
		if (nullValue(fieldValue)) {
			return;
		}

		// 如果等于某长度 那么把验证信息加入错误信息中
		String[] stringArray = inLength.split(",");
		for (int i = 0; i < stringArray.length; i++) {
			if (fieldValue.equals(stringArray[i])) {
				return;
			}
		}
		addFieldError(fieldName, object);
	}

	//fieldValue为空的判断
	private boolean nullValue(String fieldValue) {
		return (StringUtil.isNullOrEmpty(fieldValue) || fieldValue.trim().equals("")); 
	}
}
